let snake = [];
let food = {};
let direction = 'right';
let isGameRunning = false;
let gameInterval = null;
let score = 0;

function initGame() {
    const canvas = document.getElementById('snake-canvas');
    const ctx = canvas.getContext('2d');
    const scoreElement = document.getElementById('snake-score');
    const startBtn = document.getElementById('snake-start');
    const pauseBtn = document.getElementById('snake-pause');
    const resetBtn = document.getElementById('snake-reset');

    canvas.width = 400;
    canvas.height = 400;

    resetSnakeGame(ctx, canvas, scoreElement);

    startBtn.onclick = () => startGame(ctx, canvas, scoreElement);
    pauseBtn.onclick = pauseGame;
    resetBtn.onclick = () => resetSnakeGame(ctx, canvas, scoreElement);

    document.addEventListener('keydown', handleKeyDown);
}

function startGame(ctx, canvas, scoreElement) {
    if (isGameRunning) return;
    isGameRunning = true;
    gameInterval = setInterval(() => updateGame(ctx, canvas, scoreElement), 150);
}

function pauseGame() {
    isGameRunning = false;
    clearInterval(gameInterval);
}

function resetSnakeGame(ctx, canvas, scoreElement) {
    pauseGame();
    const gridSize = 20;
    snake = [
        {x: gridSize * 5, y: gridSize * 5},
        {x: gridSize * 4, y: gridSize * 5},
        {x: gridSize * 3, y: gridSize * 5}
    ];
    direction = 'right';
    score = 0;
    scoreElement.textContent = score;
    generateFood(ctx, canvas);
    drawGame(ctx, canvas);
}

function updateGame(ctx, canvas, scoreElement) {
    const head = {x: snake[0].x, y: snake[0].y};
    switch (direction) {
        case 'up': head.y -= 20; break;
        case 'down': head.y += 20; break;
        case 'left': head.x -= 20; break;
        case 'right': head.x += 20; break;
    }

    if (head.x < 0 || head.y < 0 || head.x >= canvas.width || head.y >= canvas.height ||
        snake.some(seg => seg.x === head.x && seg.y === head.y)) {
        gameOver(ctx, canvas, scoreElement);
        return;
    }

    snake.unshift(head);
    if (head.x === food.x && head.y === food.y) {
        score += 10;
        scoreElement.textContent = score;
        generateFood(ctx, canvas);
    } else {
        snake.pop();
    }
    drawGame(ctx, canvas);
}

function drawGame(ctx, canvas) {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    const gridSize = 20;
    ctx.fillStyle = '#4facfe';
    snake.forEach(seg => ctx.fillRect(seg.x, seg.y, gridSize - 1, gridSize - 1));
    ctx.fillStyle = '#ff4444';
    ctx.fillRect(food.x, food.y, gridSize - 1, gridSize - 1);
}

function generateFood(ctx, canvas) {
    const gridSize = 20;
    const gridCount = canvas.width / gridSize;
    while (true) {
        food = {
            x: Math.floor(Math.random() * gridCount) * gridSize,
            y: Math.floor(Math.random() * gridCount) * gridSize
        };
        if (!snake.some(seg => seg.x === food.x && seg.y === food.y)) break;
    }
}

function gameOver(ctx, canvas, scoreElement) {
    pauseGame();
    alert(`游戏结束！得分：${score}`);
    resetSnakeGame(ctx, canvas, scoreElement);
}

function handleKeyDown(e) {
     const isSnakeActive = document.querySelector('.snake-game.active');
    if (!isSnakeActive) return;
   
    switch(e.key) {
        case 'ArrowUp':
            if (direction !== 'down') direction = 'up';
            e.preventDefault(); // 只在游戏活跃时阻止默认行为
            break;
        case 'ArrowDown':
            if (direction !== 'up') direction = 'down';
            e.preventDefault();
            break;
        case 'ArrowLeft':
            if (direction !== 'right') direction = 'left';
            e.preventDefault();
            break;
        case 'ArrowRight':
            if (direction !== 'left') direction = 'right';
            e.preventDefault();
            break;
    }
}

function cleanupSnakeGame() {
    pauseGame();
    document.removeEventListener('keydown', handleKeyDown);
}